﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Sokoban.Model
{
    static class MapWriter
    {
        public static void SerializeMap(Map map, string mapName)
        {
            XmlWriter writer = XmlWriter.Create(Environment.CurrentDirectory + "\\" + mapName);
            writer.WriteStartDocument();
            writer.WriteStartElement("map");
            writer.WriteStartElement("name");
            writer.WriteAttributeString("val", mapName);
            writer.WriteEndElement();
            writer.WriteStartElement("x");
            writer.WriteAttributeString("val", map.GridMatrix.GetLength(1).ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("y");
            writer.WriteAttributeString("val", map.GridMatrix.GetLength(0).ToString());
            writer.WriteEndElement();
            writer.WriteStartElement("tiles");
            for (int y = 0; y < map.GridMatrix.GetLength(0); y++)
            {
                for (int x = 0; x < map.GridMatrix.GetLength(1); x++)
                {
                    writer.WriteStartElement("tile");
                    writer.WriteStartElement("x");
                    writer.WriteAttributeString("pos", x.ToString());
                    writer.WriteEndElement();
                    writer.WriteStartElement("y");
                    writer.WriteAttributeString("pos", y.ToString());
                    writer.WriteEndElement();
                    writer.WriteStartElement("type");
                    writer.WriteAttributeString("val", map.GridMatrix[y, x].ToString().ToLower());
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();


            string[] content = File.ReadAllLines(Environment.CurrentDirectory + "\\" + mapName);
            foreach (var line in content)
            {
                for (int i = 1; i < line.Length - 2; i++)
                {
                    if (line[i] == ' ' && (line[i + 1] == '>' || line[i + 1] == '/' || line[i - 1] == '<'))
                    {
                        line.Remove(i, 1);
                    }
                }
            }

            File.Delete(Environment.CurrentDirectory + "\\" + mapName);
            File.WriteAllLines(Environment.CurrentDirectory + "\\" + mapName, content);
        }
    }
}
